package com.anxin.act.task.complete.impl;

import com.anxin.act.task.cmd.UpdateNrOfInstancesCmd;
import com.anxin.act.task.complete.TaskComplete;
import com.anxin.act.task.service.ActTaskService;
import com.anxin.act.task.vo.TaskVo;
import com.anxin.act.utils.ActTaskUtils;
import com.anxin.act.utils.ActUtils;
import com.anxin.common.utils.StringUtils;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.RuntimeServiceImpl;
import org.activiti.engine.impl.bpmn.behavior.UserTaskActivityBehavior;
import org.activiti.engine.impl.interceptor.CommandExecutor;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * @author: liuxiangyu
 * @date: 2020/8/10 11:27
 */
@Service
public class BeforeTaskCompleteImpl extends TaskComplete {

    @Autowired
    private RuntimeService runtimeService;

    @Autowired
    private ActTaskCompleteImpl actTaskComplete;

    @Autowired
    private ActTaskService actTaskService;


    /**
     * 提交流程
     * @param taskVo
     */
    public String complete(TaskVo taskVo){
        List<Task> taskList = ActTaskUtils.getTaskList(taskVo.getTaskKey(), taskVo.getActId());

        Task task = ActTaskUtils.getTask(taskVo.getTaskId());
        // ActivityImpl activityImpl = ActUtils.getActivityImpl(task.getProcessDefinitionId(), task.getTaskDefinitionKey());

        if (taskList.size() == 1) {
            CommandExecutor commandExecutor = ((RuntimeServiceImpl) runtimeService).getCommandExecutor();
            commandExecutor.execute(new UpdateNrOfInstancesCmd(taskVo.getTaskId()));
        }
        //ActUtils.getActivityImpl(task.getProcessDefinitionId(),taskVo.getTaskKey());
        actTaskComplete.complete(taskVo);

        String sourceAssignee = ActTaskUtils.getTaskLocalVariable(task,"actSourceAssignee");
        String sourceTaskKey = ActTaskUtils.getTaskLocalVariable(task,"actSourceTaskKey");

        if (StringUtils.isNotBlank(sourceAssignee) && StringUtils.isNotBlank(sourceTaskKey)){
            List<Task> ruTaskList = ActTaskUtils.getTaskList(sourceTaskKey, taskVo.getActId());
            for (Task ruTask : ruTaskList) {
                if ("actAddTaskBefore".equals(ruTask.getAssignee())) {
                    taskService.setAssignee(ruTask.getId(), sourceAssignee);
                    ActTaskUtils.updateTaskStartTime(ruTask.getId());
                }
            }


        }
        return task.getId();
    }
}
